package com.jwt_demo.jwt_demo.controller;

import com.jwt_demo.jwt_demo.pojo.User;
import com.jwt_demo.jwt_demo.util.JwtUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class UserController {

    /**
     * 登录
     * @param user
     * @return
     */
    @GetMapping("/login")
    public User login(User user){
        // 数据库验证用户名密码
        // 验证成功
        Long time = 1000 * 60 * 60 * 24 * 30L;
        String token = JwtUtil.generateToken(time, user.getUsername(), user.getRole());
        user.setToken(token);
        return user;
    }

    /**
     * 获取用户信息
     * @param user
     * @return
     */
    @GetMapping("/info")
    public User info(User user){
        boolean validateToken = JwtUtil.validateToken(user.getToken());
        if(!validateToken){
            throw new RuntimeException("获取用户信息失败");
        }
        //从数据库查询用户信息
        return user;
    }

    /**
     * 获取用户信息
     * @param
     * @return
     */
    @GetMapping("/info2")
    public User info2(HttpServletRequest request){
        String token = request.getHeader("token");
        boolean validateToken = JwtUtil.validateToken(token);
        if(!validateToken){
            throw new RuntimeException("获取用户信息失败");
        }
        //从数据库查询用户信息
        User user = new User();
        return user;
    }
}

